package test;

import glapp.GLApp;

import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Vector3f;

public class CameraG3d {

	/**
	 * X axes rotation
	 */
	private float pitch = 0;
	/**
	 * 
	 * Y axes rotation
	 */
	private float yawl;
	public boolean forward = false;
	public boolean backward = false;
	public boolean right = false;
	public boolean left = false;
	private Vector3f orig;
	private float x, y, z;

	public CameraG3d(Vector3f poo) {
		orig = poo;
		x = orig.x;

	}

	/**
	 * calculate position of camera after moving in directon distance
	 * 
	 * @param distance
	 * @param direction
	 */
	public void moveCamera(float distance, float direction) {
		float rad = (float) ((yawl + direction) * Math.PI / 180.0f);
		orig.x -= Math.sin(rad) * distance;
		orig.z -= Math.cos(rad) * distance;

	}

	public void moveCameraUp(float distance, float direction) {
		float rad = (float) ((pitch + direction) * Math.PI / 180.0f);
		orig.y -= Math.sin(rad) * distance;
		System.out.println(orig.y);
	}

	/**
	 * Lock yawl between 360 0 and pitch -90 - 90 degrees
	 */
	private void lockCameraAngels() {
		if (pitch > 90.0f) {
			pitch = 90.0f;
		} else if (pitch < -90.0f) {
			pitch = -90.0f;
		}

		if (yawl < 0.0f) {
			yawl += 360;
		} else if (yawl > 360.0f) {
			yawl -= 360;
		}

	}

	/**
	 * Calculate the position of camarea and angels, by steplenght and factor
	 * 
	 * @param steplenght
	 * @param mousesens
	 */
	int oldX = Mouse.getX();
	int oldY = Mouse.getY();

	public void CamKeysListener(float steplenght, float mousesens) {

		int mdx = 0;
		int mdy = 0;
		// Mouse.setGrabbed(true);
		int midX = Display.getWidth() / 2;
		int midY = Display.getHeight() / 2;
		//if (Mouse.isButtonDown(0)) {
			mdx = GLApp.mouseDX;
			mdy = GLApp.mouseDY;
		//} else {
			//mdx = 0;
			//mdy = 0;
		//}
		int mx = mdx;// Mouse.getDX();
		int my = mdy; // Mouse.getDY();

		oldX = Mouse.getX();
		oldY = Mouse.getY();
		yawl -= mousesens * (mx);
		pitch += mousesens * (my);
		System.out.println("Yawl: " + yawl);
		System.out.println("Pitch: " + pitch);
		lockCameraAngels();
		// Mouse.setCursorPosition(midX, midY);

		if (backward) {
			if (pitch != 89f && pitch != -89f) {
				moveCamera(steplenght, 180.0f);
				moveCameraUp(steplenght, 180.0f);
			}// forward
		} else if (forward) {
			if (pitch != 89f && pitch != -89f) {
				moveCamera(steplenght, 0.0f);
				moveCameraUp(steplenght, 0.0f);
			}
		}// backward

		if (left) {
			moveCamera(steplenght, 90.0f);
			moveCameraUp(steplenght, 90.0f);
		} // left
		else if (right) {
			moveCamera(steplenght, 270.0f);
			moveCameraUp(steplenght, 270.0f);
		}// roight
		GL11.glRotatef(-pitch, 1.0f, 0.0f, 0.0f);
		GL11.glRotatef(-yawl, 0.0f, 1.0f, 0.0f);

	}

	/**
	 * update position of scene to new camera location
	 */
	public void UpdateCamera() {
		GL11.glTranslatef(-orig.x, -1, -orig.y);
	}
}
